package com.yiba.logutils.save.impl;

import com.yiba.logutils.save.ILogFormatter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class LogFormatter implements ILogFormatter {

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);
    private final StringBuilder content = new StringBuilder();

    @Override
    public String format(String msg, boolean crypt) {
        if (content.length() > 0) {
            content.delete(0, content.length());
        }
        content.append("#!");
        content.append(getTime());
        content.append("#!");
        content.append(msg);
        if (!crypt) {
            content.append('\n');
        }
        return content.toString();
    }

    @Override
    public String format(List<String> msgFieldList, boolean crypt) {
        if (content.length() > 0) {
            content.delete(0, content.length());
        }
        content.append("#!");
        content.append(getTime());
        content.append("#!");
        int size = msgFieldList.size();
        for (int i = 0; i < size; ++i) {
            content.append(msgFieldList.get(i));
            if (i < size - 1) {
                content.append("#*");
            }
        }
        if (!crypt) {
            content.append('\n');
        }
        return content.toString();
    }

    private String getTime() {
        return sdf.format(Calendar.getInstance().getTime());
    }
}
